﻿using System;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Timers;
using NegTask;
using Timer = System.Timers.Timer;

namespace ServicioTask
{
    public partial class Activacion : ServiceBase
    {
        private static Timer _timer;
        private static string _LogFileName;
        private static string strError = "Ha ocurrido el siguiente error a las '[FechaHora]': \nMétodo:[Metodo]\nMensaje de Error:[MsgError]";

        public Activacion()
        {
            InitializeComponent();

            var _Hoy = DateTime.Now;
            _LogFileName = ConfigurationManager.AppSettings["ArchivoLog"].Replace("[Fecha]", _Hoy.ToString("yyyymmdd"));

            //nVeces = 0;
        }

        private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Enabled = false;
            
            try
            {
                if (ConfigurationManager.AppSettings["Activo"] == "S")
                {
                    NegTask.Cls_Task Tareas = new NegTask.Cls_Task();
                    Tareas.GetTasks();


                }
                LogFile("LogFile(ConfigurationManager.AppSettings[Activo]" + ConfigurationManager.AppSettings["Activo"]);
                                
            }
            catch (Exception ex)
            {
                strError = strError.Replace("[FechaHora]", DateTime.Now.ToShortTimeString());
                strError = strError.Replace("[Metodo]", "'_timer_Elapsed'");
                strError = strError.Replace("[MsgError]", ex.Message);

                LogFile(strError);
            }

            _timer.Enabled = true;
        }

        protected override void OnStart(string[] args)
        {
            try
            {                
             
                NegTask.Cls_Task.UpdateEstadoTarea(0, 0);
                 
                LogFile("*=============================================================* \n");
                LogFile(" Servicio Iniciado el " + DateTime.Now.ToShortDateString() + " a las " + DateTime.Now.ToShortTimeString());
                LogFile("*=============================================================* \n");


                _timer = new Timer
                             {
                                 Interval = Convert.ToDouble(ConfigurationManager.AppSettings["IntervaloEjecucion"])
                             };
                _timer.Elapsed += _timer_Elapsed;
                _timer.Enabled = true;
                _timer.Start();
                              


            }
            catch (Exception ex)
            {
                strError = strError.Replace("[FechaHora]", DateTime.Now.ToShortTimeString());
                strError = strError.Replace("[Metodo]", "'Servicio: OnStart'");
                strError = strError.Replace("[MsgError]", ex.Message);

                LogFile(strError);
            }
        }

        protected override void OnContinue()
        {
            try
            {
                if (_timer == null) return;

                LogFile("Servicio Continuado el " + DateTime.Now.ToShortDateString() + " a las " + DateTime.Now.ToShortTimeString());

                _timer.Enabled = true;
                _timer.Start();
            }
            catch (Exception ex)
            {
                strError = strError.Replace("[FechaHora]", DateTime.Now.ToShortTimeString());
                strError = strError.Replace("[Metodo]", "'Servicio: OnContinue'");
                strError = strError.Replace("[MsgError]", ex.Message);

                LogFile(strError);
            }
        }

        protected override void OnPause()
        {
            try
            {
                if (_timer == null) return;

                LogFile("*=============================================================* \n");
                LogFile(" Servicio Pausado \n" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
                LogFile("*=============================================================* \n");

                _timer.Enabled = false;
                _timer.Stop();
            }
            catch (Exception ex)
            {
                strError = strError.Replace("[FechaHora]", DateTime.Now.ToShortTimeString());
                strError = strError.Replace("[Metodo]", "'Servicio: OnPause'");
                strError = strError.Replace("[MsgError]", ex.Message);

                LogFile(strError);
            }
        }

        protected override void OnStop()
        {
            try
            {
                if (_timer == null) return;

                LogFile("*=============================================================* \n");
                LogFile(" Servicio Detenido \n" + DateTime.Now.ToShortDateString() + " a las " + DateTime.Now.ToShortTimeString());
                LogFile("*=============================================================* \n");

                _timer.Enabled = false;
                _timer.Stop();
            }
            catch (Exception ex)
            {
                strError = strError.Replace("[FechaHora]", DateTime.Now.ToShortTimeString());
                strError = strError.Replace("[Metodo]", "'Servicio: OnStop'");
                strError = strError.Replace("[MsgError]", ex.Message);

                LogFile(strError);
            }
        }

        protected static void LogFile(string archivoLog, string mensaje)
        {
            var fs = new FileStream(archivoLog, FileMode.OpenOrCreate, FileAccess.Write);
            var m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(mensaje);
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

        protected static void LogFile(string mensaje)
        {
            LogFile(_LogFileName, mensaje);
        }
              
    }
}